
import six

from keras.layers.merge import add
from keras.layers.normalization import BatchNormalization
from keras.regularizers import l2
from keras import backend as K
from keras.layers import Input,Activation,Flatten,Dense,Conv2D,MaxPool2D,Conv2DTranspose,concatenate
from keras.models import Model
from keras.losses import binary_crossentropy
from keras.callbacks import ModelCheckpoint,EarlyStopping,ReduceLROnPlateau,TensorBoard


def _bn_relu(input):
    """Helper to build a BN -> relu block
    """
    norm = BatchNormalization(axis=CHANNEL_AXIS)(input)
    return Activation("relu")(norm)


def _conv_bn_relu(**conv_params):
    """Helper to build a conv -> BN -> relu block
    """
    filters = conv_params["filters"]
    kernel_size = conv_params["kernel_size"]
    strides = conv_params.setdefault("strides", (1, 1))
    kernel_initializer = conv_params.setdefault("kernel_initializer", "he_normal")
    padding = conv_params.setdefault("padding", "same")
    kernel_regularizer = conv_params.setdefault("kernel_regularizer", l2(1.e-4))

    def f(input):
        conv = Conv2D(filters=filters, kernel_size=kernel_size,
                      strides=strides, padding=padding,
                      kernel_initializer=kernel_initializer,
                      kernel_regularizer=kernel_regularizer)(input)
        return _bn_relu(conv)

    return f


def _bn_relu_conv(**conv_params):
    """Helper to build a BN -> relu -> conv block.
    This is an improved scheme proposed in http://arxiv.org/pdf/1603.05027v2.pdf
    """
    filters = conv_params["filters"]
    kernel_size = conv_params["kernel_size"]
    strides = conv_params.setdefault("strides", (1, 1))
    kernel_initializer = conv_params.setdefault("kernel_initializer", "he_normal")
    padding = conv_params.setdefault("padding", "same")
    kernel_regularizer = conv_params.setdefault("kernel_regularizer", l2(1.e-4))

    def f(input):
        activation = _bn_relu(input)
        return Conv2D(filters=filters, kernel_size=kernel_size,
                      strides=strides, padding=padding,
                      kernel_initializer=kernel_initializer,
                      kernel_regularizer=kernel_regularizer)(activation)

    return f


def _shortcut(input, residual):
    """Adds a shortcut between input and residual block and merges them with "sum"
    """
    # Expand channels of shortcut to match residual.
    # Stride appropriately to match residual (width, height)
    # Should be int if network architecture is correctly configured.
    input_shape = K.int_shape(input)
    residual_shape = K.int_shape(residual)
    stride_width = int(round(input_shape[ROW_AXIS] / residual_shape[ROW_AXIS]))
    stride_height = int(round(input_shape[COL_AXIS] / residual_shape[COL_AXIS]))
    equal_channels = input_shape[CHANNEL_AXIS] == residual_shape[CHANNEL_AXIS]

    shortcut = input
    # 1 X 1 conv if shape is different. Else identity.
    if stride_width > 1 or stride_height > 1 or not equal_channels:
        shortcut = Conv2D(filters=residual_shape[CHANNEL_AXIS],
                          kernel_size=(1, 1),
                          strides=(stride_width, stride_height),
                          padding="valid",
                          kernel_initializer="he_normal",
                          kernel_regularizer=l2(0.0001))(input)

    return add([shortcut, residual])


def _residual_block(block_function, filters, repetitions, is_first_layer=False):
    """Builds a residual block with repeating bottleneck blocks.
    """
    def f(input):
        for i in range(repetitions):
            init_strides = (1, 1)
            if i == 0 and not is_first_layer:
                init_strides = (2, 2)
            input = block_function(filters=filters, init_strides=init_strides,
                                   is_first_block_of_first_layer=(is_first_layer and i == 0))(input)
        return input

    return f


def basic_block(filters, init_strides=(1, 1), is_first_block_of_first_layer=False):
    """Basic 3 X 3 convolution blocks for use on resnets with layers <= 34.
    Follows improved proposed scheme in http://arxiv.org/pdf/1603.05027v2.pdf
    """
    def f(input):

        if is_first_block_of_first_layer:
            # don't repeat bn->relu since we just did bn->relu->maxpool
            conv1 = Conv2D(filters=filters, kernel_size=(3, 3),
                           strides=init_strides,
                           padding="same",
                           kernel_initializer="he_normal",
                           kernel_regularizer=l2(1e-4))(input)
        else:
            conv1 = _bn_relu_conv(filters=filters, kernel_size=(3, 3),
                                  strides=init_strides)(input)

        residual = _bn_relu_conv(filters=filters, kernel_size=(3, 3))(conv1)
        return _shortcut(input, residual)

    return f


def bottleneck(filters, init_strides=(1, 1), is_first_block_of_first_layer=False):
    """Bottleneck architecture for > 34 layer resnet.
    Follows improved proposed scheme in http://arxiv.org/pdf/1603.05027v2.pdf

    Returns:
        A final conv layer of filters * 4
    """
    def f(input):

        if is_first_block_of_first_layer:
            # don't repeat bn->relu since we just did bn->relu->maxpool
            conv_1_1 = Conv2D(filters=filters, kernel_size=(1, 1),
                              strides=init_strides,
                              padding="same",
                              kernel_initializer="he_normal",
                              kernel_regularizer=l2(1e-4))(input)
        else:
            conv_1_1 = _bn_relu_conv(filters=filters, kernel_size=(1, 1),
                                     strides=init_strides)(input)

        conv_3_3 = _bn_relu_conv(filters=filters, kernel_size=(3, 3))(conv_1_1)
        residual = _bn_relu_conv(filters=filters * 4, kernel_size=(1, 1))(conv_3_3)
        return _shortcut(input, residual)

    return f


def _handle_dim_ordering():
    global ROW_AXIS
    global COL_AXIS
    global CHANNEL_AXIS
    if K.image_dim_ordering() == 'tf':
        ROW_AXIS = 1
        COL_AXIS = 2
        CHANNEL_AXIS = 3
    else:
        CHANNEL_AXIS = 1
        ROW_AXIS = 2
        COL_AXIS = 3


def _get_block(identifier):
    if isinstance(identifier, six.string_types):
        res = globals().get(identifier)
        if not res:
            raise ValueError('Invalid {}'.format(identifier))
        return res
    return identifier


class RSSegResNet(object):
    @staticmethod
    def build(input_shape, num_outputs, block_fn, repetitions):
        """Builds a custom ResNet like architecture.

        Args:
            input_shape: The input shape in the form (nb_channels, nb_rows, nb_cols)
            num_outputs: The number of outputs at final softmax layer
            block_fn: The block function to use. This is either `basic_block` or `bottleneck`.
                The original paper used basic_block for layers < 50
            repetitions: Number of repetitions of various block units.
                At each block unit, the number of filters are doubled and the input size is halved

        Returns:
            The keras `Model`.
        """
        _handle_dim_ordering()
        if len(input_shape) != 3:
            raise Exception("Input shape should be a tuple (nb_channels, nb_rows, nb_cols)")

        # Permute dimension order if necessary
        if K.image_dim_ordering() == 'tf':
            input_shape = (input_shape[1], input_shape[2], input_shape[0])

        # Load function from str if needed.
        block_fn = _get_block(block_fn)

        # define model
        image_input = Input(input_shape, name='image_input') # (None, 288,288,3)

        # conv1
        filters = 64
        conv1 = _conv_bn_relu(filters=filters, kernel_size=(7, 7), strides=(2, 2))(image_input)
        # (None, 144,144,64)

        # conv2.x
        conv2 = MaxPool2D(pool_size=(3, 3), strides=(2, 2), padding="same")(conv1)
        # (None, 72,72,64)
        conv2 = _residual_block(block_fn, filters=filters,
                                repetitions=repetitions[0], is_first_layer=True)(conv2) # strides=1
        # (None, 72,72,256)

        # conv3.x
        filters *= 2 # 128
        conv3 = _residual_block(block_fn, filters=filters,
                                repetitions=repetitions[1], is_first_layer=False)(conv2)
        # (None, 36,36,512)

        # conv4.x
        filters *= 2  # 256
        conv4 = _residual_block(block_fn, filters=filters,
                                repetitions=repetitions[2], is_first_layer=False)(conv3)
        # (None, 18,18,1024)

        # conv5.x
        filters *= 2  # 512
        conv5 = _residual_block(block_fn, filters=filters,
                                repetitions=repetitions[3], is_first_layer=False)(conv4)
        # (None, 9,9,2048)

        # center
        center = Conv2D(2048, 3, activation='relu', padding='same')(conv5)
        # (None, 9,9,2048)

        # decoder part
        db5 = Conv2D(2048, 3, activation='relu', padding='same')(center)
        db5 = concatenate([db5, conv5], axis=3)
        db5 = Conv2DTranspose(512, 3, strides=(2, 2), activation='relu', padding='same')(db5)
        # (None, 18, 18, 512)

        db4 = Conv2D(512, 3, activation='relu', padding='same')(db5)
        db4 = concatenate([db4, conv4], axis=3)
        db4 = Conv2DTranspose(256, 3, strides=(2, 2), activation='relu', padding='same')(db4)
        # (None, 36, 36, 256)

        db3 = Conv2D(256, 3, activation='relu', padding='same')(db4)
        db3 = concatenate([db3, conv3], axis=3)
        db3 = Conv2DTranspose(128, 3, strides=(2, 2), activation='relu', padding='same')(db3)
        # (None, 72,72,128)

        db2 = Conv2D(128, 3, activation='relu', padding='same')(db3)
        db2 = concatenate([db2, conv2], axis=3)
        db2 = Conv2DTranspose(64, 3, strides=(2, 2), activation='relu', padding='same')(db2)
        # (None, 144, 144, 64)

        db1 = Conv2D(64, 3, activation='relu', padding='same')(db2)
        db1 = concatenate([db1, conv1], axis=3)
        db1 = Conv2DTranspose(32, 3, strides=(2, 2), activation='relu', padding='same')(db1)
        # (None, 288,288, 32)

        output = Conv2D(32, 3, activation='relu', padding='same')(db1)
        output = Conv2D(num_outputs, 3, activation='sigmoid', padding='same')(output)

        model = Model(inputs=image_input, outputs=output)
        return model

    @staticmethod
    def build_resnet_18(input_shape, num_outputs):
        return RSSegResNet.build(input_shape, num_outputs, basic_block, [2, 2, 2, 2])

    @staticmethod
    def build_resnet_34(input_shape, num_outputs):
        return RSSegResNet.build(input_shape, num_outputs, basic_block, [3, 4, 6, 3])

    @staticmethod
    def build_resnet_50(input_shape, num_outputs):
        return RSSegResNet.build(input_shape, num_outputs, bottleneck, [3, 4, 6, 3])

    @staticmethod
    def build_resnet_101(input_shape, num_outputs):
        return RSSegResNet.build(input_shape, num_outputs, bottleneck, [3, 4, 23, 3])

    @staticmethod
    def build_resnet_152(input_shape, num_outputs):
        return RSSegResNet.build(input_shape, num_outputs, bottleneck, [3, 8, 36, 3])